package com.xoa.service.documentOrg;

import com.xoa.dao.WFE.WFEFlowRunMapper;
import com.xoa.dao.document.DocumentMapper;
import com.xoa.dao.documentOrg.DocumentOrgMapper;
import com.xoa.dao.enclosure.AttachmentMapper;
import com.xoa.dao.users.OrgManageMapper;
import com.xoa.dao.workflow.FlowRunMapper;
import com.xoa.model.document.DocumentModelWithBLOBs;
import com.xoa.model.document.DocumentWithBLOBs;
import com.xoa.model.documentOrg.DocumentOrg;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.users.OrgManage;
import com.xoa.model.users.Users;
import com.xoa.model.workflow.FlowRun;
import com.xoa.service.document.DocumentSerivce;
import com.xoa.service.enclosure.EnclosureService;
import com.xoa.service.users.OrgManageService;
import com.xoa.util.*;
import com.xoa.util.common.L;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.dataSource.ContextHolder;
import com.xoa.util.page.PageParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2018/3/13.
 */
@Service
public class DocumentOrgService {

    @Autowired
    DocumentOrgMapper documentOrgMapper;

    @Autowired
    DocumentSerivce documentSerivce;

    @Autowired
    AttachmentMapper attachmentMapper;

    @Autowired
    OrgManageService orgManageService;

    @Autowired
    private WFEFlowRunMapper wfeFlowRunMapper;

    @Resource
    private OrgManageMapper orgManageMapper;


    public ToJson querylistId(HttpServletRequest request,String id) {
        ToJson  toJson=new ToJson(1, "false");
        Set<String> set=new HashSet<>();
        Map map=new HashMap();
        try {
            // 获取初始组织并存放
            String firstDBSource = "xoa" + (String) request.getSession().getAttribute("loginDateSouse");
            Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users nowUser = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId);
            //查询当前库的公文
            List<DocumentOrg> documentOrgs = documentOrgMapper.selectDocumentOrgtitle(documentOrgMapper.selOldDocById(Integer.parseInt(id)));
            for (DocumentOrg docu:documentOrgs) {
                if (!StringUtils.checkNull(docu.getTransferReceiveOrg())) {
                    String[] split = docu.getTransferReceiveOrg().split(",");
                    for (String loginId : split) {
                        // 要切换的库
                        String dbSource = "xoa" + loginId;
                        // 数据库切换
                        ContextHolder.setConsumerType(dbSource);
                        map.put("tableSchema",dbSource);
                        map.put("tableName","document_org");
                        //仅仅为了判断某个库是否存在这张表
                        int istable = documentOrgMapper.istable(map);
                        if (istable>0){
                            //存在直接查询是否有这条公文
                            List<DocumentOrg> list1 = documentOrgMapper.selectByRunId(docu);
                            if ((list1.size()>0)){
                                set.add(loginId);
                            }
                        }
                    }
                    ContextHolder.setConsumerType(firstDBSource);
                }
            }
            List<OrgManage>  org;
            if(set.size()>0){
                org=orgManageMapper.querylistId(new ArrayList(set));
            }else{
                org=orgManageMapper.queryId();
            }
            if(org.size()>0){
                toJson.setFlag(0);
                toJson.setMsg("ok");
                toJson.setObj(org);
            }
        }catch (Exception e){
            toJson.setMsg(e.toString());
            e.printStackTrace();
        }
        return toJson;
    }


    /**
     * 作者: 张航宁
     * 日期: 2018/3/14
     * 说明: 上级来文转公文
     */
    public ToJson<Object> saveToDocument(HttpServletRequest request, Integer id, Integer flowId, String documentType) {
        ToJson<Object> json = new ToJson<Object>();
        try {
            Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users nowUser = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId);

            DocumentModelWithBLOBs documentModelWithBLOBs = documentOrgMapper.selDocumentOrgById(id);
            documentModelWithBLOBs.setDocumentType(documentType);
            documentModelWithBLOBs.setFlowId(flowId);
            documentModelWithBLOBs.setCreater(nowUser.getUserId());
            documentModelWithBLOBs.setCurUserId(nowUser.getUserId());
            documentModelWithBLOBs.setCreater(nowUser.getUserId());
            documentModelWithBLOBs.setCreateDept(nowUser.getDeptId().toString());
            String cureTime = DateFormat.getCurrentTime2();
            documentModelWithBLOBs.setPrintDate(cureTime);
            if (documentModelWithBLOBs != null) {
                json = documentSerivce.saveDocument(nowUser, flowId, 1, "1", documentModelWithBLOBs.getTitle(), documentModelWithBLOBs, request);
                // 更新转交状态
                documentOrgMapper.updateTransferFlag(id, 1);
            }

            json.setMsg("ok");
            json.setFlag(0);
        } catch (Exception e) {
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg("err");
        }
        return json;
    }

    /**
     * 作者: 张航宁
     * 日期: 2018/3/14
     * 说明: 获取当前上级来文
     */
    public ToJson<DocumentOrg> selDocumentOrg(DocumentOrg documentOrg, HttpServletRequest request, PageParams pageParams) {
        ToJson<DocumentOrg> json = new ToJson<DocumentOrg>();
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("page", pageParams);
            List<DocumentOrg> documentOrgs = documentOrgMapper.selDocumentOrg(map);
            json.setTotleNum(pageParams.getTotal());
            json.setObj(documentOrgs);
            json.setFlag(0);
            json.setMsg("ok");
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg("err:" + e);
            json.setFlag(1);
        }
        return json;
    }


    /*<!--查询库中document_org表transfer_flag字段是否办理下发文件-->未接收*/
    public List<OrgManage> selectDocumentOrgIsConduct(DocumentOrg documentOrg, HttpServletRequest request){
        List<OrgManage> list = null;
        try {
            // 获取初始组织并存放
            String firstDBSource = "xoa" + (String) request.getSession().getAttribute("loginDateSouse");
            List<DocumentOrg> documentOrgs = documentOrgMapper.selectDocumentOrgIsConduct(documentOrg);
            list = new ArrayList<>();
            // for(DocumentOrg docu : documentOrgs) {
            if (documentOrgs.size()>0){
                DocumentOrg docu = documentOrgs.get(0);
                if (!StringUtils.checkNull(docu.getTransferReceiveOrg())) {
                    String[] split = docu.getTransferReceiveOrg().split(",");
                    for (String loginId : split) {
                        // 要切换的库
                        String dbSource = "xoa" + loginId;
                        // 数据库切换
                        ContextHolder.setConsumerType(dbSource);
                        List<DocumentOrg> list1 = documentOrgMapper.selectByRunId(documentOrg);
                        for (DocumentOrg list2 : list1) {
                            if (list2.getTransferFlag() == 0) {
                                ContextHolder.setConsumerType("xoa1001");
                                List<OrgManage> orgManage = orgManageService.getOrgManage();
                                for (OrgManage orgManages : orgManage) {
                                    if (orgManages.getOid() == Integer.parseInt(loginId)) {
                                        list.add(orgManages);
                                    }
                                }
                            }
                        }

                    }
                    ContextHolder.setConsumerType(firstDBSource);
                }
            }

            // }
        } catch (Exception e) {
            String s=e.toString();
            if(s.indexOf("doesn't exist")!=-1){
                System.out.println("没有此表");
            }
        }
        return list;
    }

    /*<!--查询库中document_org表transfer_flag字段是否办理下发文件-->已接收*/
    public List<OrgManage> selectDocumentOrgIsConducts(DocumentOrg documentOrg, HttpServletRequest request){
        List<OrgManage> list = null;
        try {
            // 获取初始组织并存放
            String firstDBSource = "xoa" + (String) request.getSession().getAttribute("loginDateSouse");
            List<DocumentOrg> documentOrgs = documentOrgMapper.selectDocumentOrgIsConduct(documentOrg);
            list = new ArrayList<>();
            // for(DocumentOrg docu : documentOrgs) {
            if (documentOrgs.size()>0){
                DocumentOrg docu = documentOrgs.get(0);
                if (!StringUtils.checkNull(docu.getTransferReceiveOrg())) {
                    String[] split = docu.getTransferReceiveOrg().split(",");
                    for (String loginId : split) {
                        // 要切换的库
                        String dbSource = "xoa" + loginId;
                        // 数据库切换
                        ContextHolder.setConsumerType(dbSource);
                        List<DocumentOrg> list1 = documentOrgMapper.selectByRunId(documentOrg);
                        for (DocumentOrg list2 : list1) {
                            if (list2.getTransferFlag() == 1) {
                                ContextHolder.setConsumerType("xoa1001");
                                List<OrgManage> orgManage = orgManageService.getOrgManage();
                                ContextHolder.setConsumerType(dbSource);
                                for (OrgManage orgManages : orgManage) {
                                    if (orgManages.getOid() == Integer.parseInt(loginId)) {
                                        Map map=new HashMap();
                                        map.put("runId",list2.getRunId());
                                        //BEGIN_TIME创建时间
                                        FlowRun flowRun = wfeFlowRunMapper.find(map);
                                        if (flowRun!=null){
                                            orgManages.setName(orgManages.getName()+"("+flowRun.getBeginTime()+")");
                                            list.add(orgManages);
                                        }

                                    }
                                }
                            }
                        }

                    }
                    ContextHolder.setConsumerType(firstDBSource);
                }
            }

            // }
        } catch (Exception e) {
            String s=e.toString();
            if(s.indexOf("doesn't exist")!=-1){
                System.out.println("没有此表");
            }
        }
        return list;
    }



    /**
     * 作者: 张航宁
     * 日期: 2018/3/14
     * 说明: 上级发文到下级
     */
    public ToJson<DocumentOrg> saveDoc(Integer id, DocumentOrg documentOrg, HttpServletRequest request) {
        ToJson<DocumentOrg> json = new ToJson<DocumentOrg>();
        Map map=new HashMap();
        try {
            DocumentOrg oldDocumentOrg = documentOrgMapper.selOldDocById(id);
            // 获取初始组织并存放
            String firstDBSource = "xoa" + (String) request.getSession().getAttribute("loginDateSouse");
            Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users nowUser = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId);

            oldDocumentOrg.setOrgFlag(1);
            oldDocumentOrg.setTransferFlag(0);

            oldDocumentOrg.setTransferOrg(firstDBSource.replace("xoa", ""));
            oldDocumentOrg.setTransferUser(nowUser.getUserId());

            oldDocumentOrg.setTransferReceiveOrg(documentOrg.getTransferReceiveOrg());
            oldDocumentOrg.setTransferReceiveUser(documentOrg.getTransferReceiveUser());

            oldDocumentOrg.setTransferTime(new Date());

            //判断是否是发起人
            if(oldDocumentOrg.getRunId()!=null){
                // 插入一条记录到 发起库表
                documentOrgMapper.insertSelective(oldDocumentOrg);

                // 切库进行切库后的插入操作 以及附件转存
                // 设置组织为下级组织
                oldDocumentOrg.setOrgFlag(0);

                //当前登录库正文
                String currentMainFile=oldDocumentOrg.getMainFile(); //正文号
                if (!StringUtils.checkNull(oldDocumentOrg.getTransferReceiveOrg())) {
                    String[] split = oldDocumentOrg.getTransferReceiveOrg().split(",");
                    for (String loginId : split) {
                        // 要切换的库
                        String dbSource = "xoa" + loginId;
                        if (!firstDBSource.equals(dbSource)) {

                            // 复制文件到新的库   正文
                            copyWordAndAIPFile(null,oldDocumentOrg, firstDBSource, dbSource);
                            // 数据库切换
                            ContextHolder.setConsumerType(dbSource);
                            map.put("tableSchema",dbSource);
                            map.put("tableName","document_org");
                            //进行保存接口前判断这个库是否存在这张表
                            int istable = documentOrgMapper.istable(map);
                            if (istable==0) {
                                //创建表
                                documentOrgMapper.createTable();
                            }
                            // 进行保存接口.保存是无论怎样都要走的
                            documentOrgMapper.insertSelective(oldDocumentOrg);
                        }
                        // 切换回当前库
                        ContextHolder.setConsumerType(firstDBSource);
                        oldDocumentOrg.setMainFile(currentMainFile); //切回原来库的时候把原来库的正文给还原
                    }
                }

                json.setFlag(0);
                json.setMsg("ok");
            }
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg("err:" + e);
            json.setFlag(1);
        }
        return json;
    }

    /**
     * 说明: 根据流水号与转交后的接收组织进行查看是否已下发过一次
     */
    public boolean select(Integer id, DocumentOrg documentOrg, HttpServletRequest request) {
        try {
            DocumentOrg oldDocumentOrg = documentOrgMapper.selOldDocById(id);
            // 获取初始组织并存放
            String firstDBSource = "xoa" + (String) request.getSession().getAttribute("loginDateSouse");
            Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users nowUser = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId);


            oldDocumentOrg.setTransferReceiveOrg(documentOrg.getTransferReceiveOrg());

            // 切库进行切库后的插入操作 以及附件转存
            if (!StringUtils.checkNull(oldDocumentOrg.getTransferReceiveOrg())) {
                String[] split = oldDocumentOrg.getTransferReceiveOrg().split(",");
                for (String loginId : split) {
                    // 要切换的库
                    String dbSource = "xoa" + loginId;
                    // 数据库切换
                    ContextHolder.setConsumerType(dbSource);
                    // 进行查询的接口
                    List<DocumentOrg> list = documentOrgMapper.selectByRunId(oldDocumentOrg);
                    if(list.size()>0){
                        return false;
                    } else {
                        return true;
                    }
                }
                // 切换回当前库
                ContextHolder.setConsumerType(firstDBSource);

            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 作者: 张航宁
     * 日期: 2018/3/14
     * 说明: 拷贝word和aip文件到新的库文件夹
     */
    public void copyWordAndAIPFile(FlowRun flowRun,DocumentOrg documentOrg, String firstDBSource, String dbSource) throws IOException {
        ResourceBundle rb = ResourceBundle.getBundle("upload");
        String osName = System.getProperty("os.name");
        StringBuffer sb = new StringBuffer();
        StringBuffer buffer=new StringBuffer();
        if(osName.toLowerCase().startsWith("win")){
            //sb=sb.append(rb.getString("upload.win"));
            //判断路径是否是相对路径，如果是的话，加上运行的路径
            String uploadPath = rb.getString("upload.win");
            if(uploadPath.indexOf(":")==-1){
                //获取运行时的路径
                String basePath = this.getClass().getClassLoader().getResource(".").getPath()+ File.pathSeparator;
                //获取截取后的路径
                String str2 = "";
                if(basePath.indexOf("/xoa")!=-1){
                    //获取字符串的长度
                    int length = basePath.length();
                    //返回指定字符在此字符串中第一次出现处的索引
                    int index = basePath.indexOf("/xoa");
                    //从指定位置开始到指定位置结束截取字符串
                    str2=basePath.substring(0,index);
                }
                sb = sb.append(str2 + "/xoa");
            }
            sb.append(uploadPath);
            buffer=buffer.append(rb.getString("upload.win"));
        }else{
            sb=sb.append(rb.getString("upload.linux"));
            buffer=buffer.append(rb.getString("upload.linux"));
        }

        if ((flowRun!=null && !StringUtils.checkNull(flowRun.getAttachmentId()) && !StringUtils.checkNull(flowRun.getAttachmentName()))|| (documentOrg!=null && !StringUtils.checkNull(documentOrg.getMainFile()) && !StringUtils.checkNull(documentOrg.getMainFileName()))) {
            List<Attachment> attachments = null;
            if (documentOrg!=null){
                attachments=GetAttachmentListUtil.returnAttachment(documentOrg.getMainFileName(), documentOrg.getMainFile(), firstDBSource, "document");
            }else if (flowRun!=null){
                attachments=GetAttachmentListUtil.returnAttachment(flowRun.getAttachmentName(), flowRun.getAttachmentId(), firstDBSource, "workflow");
            }
            if (attachments != null && attachments.size() > 0) {
                StringBuffer stringBuffer=new StringBuffer();
                for (Attachment attachment:attachments) {

                    // 获取文件path
//                String path = sb.toString() + System.getProperty("file.separator") + "attach" + System.getProperty("file.separator") + firstDBSource +
//                        System.getProperty("file.separator") + "document" + System.getProperty("file.separator") + attachment.getYm() + System.getProperty("file.separator") + attachment.getAttachId() + "." + attachment.getAttachName();

                    //---------------------------------判断是否为Linux开始-------------------------------------


                    String attachmentName = attachment.getAttachName();
                    try {
                        int codeLength = attachmentName.getBytes("UTF-8").length;
                        String type = attachmentName.substring(attachmentName.lastIndexOf("."));
                        if(codeLength>230&&osName.toLowerCase().startsWith("linu")){//判断
                            String s = (new BASE64Encoder()).encodeBuffer((attachmentName.substring(0,attachmentName.lastIndexOf("."))).getBytes(StandardCharsets.UTF_8));
                            String regEx=("[\\s\\\\/:\\*\\?\\\"<>\\|]");
                            attachmentName=(Pattern.compile(regEx).matcher(s).replaceAll("").trim().substring(0,100))+type;
                        }
                    }catch (Exception e){

                    }

                    //---------------------------------判断是否为Linux结束-------------------------------------

                    String path = null;
                    if (documentOrg!=null){
                        path=sb.toString() + System.getProperty("file.separator") + firstDBSource +
                                System.getProperty("file.separator") + "document" + System.getProperty("file.separator") + attachment.getYm() + System.getProperty("file.separator") + attachment.getAttachId() + "." + attachmentName;
                    }else if (flowRun!=null){
                        path=sb.toString() + System.getProperty("file.separator") + firstDBSource +
                                System.getProperty("file.separator") + "workflow" + System.getProperty("file.separator") + attachment.getYm() + System.getProperty("file.separator") + attachment.getAttachId() + "." + attachmentName;
                    }


                    File file = new File(path);
                    // 如果文件不存在
                    if (!file.exists()) {
                        if (documentOrg!=null){
                            documentOrg.setMainFile("");
                            documentOrg.setMainFileName("");
                        }else if (flowRun!=null){
                            flowRun.setAttachmentId("");
                            flowRun.setAttachmentName("");
                        }
                    } else {
                        String attachID =String.valueOf(Math.abs((int) System.currentTimeMillis())) ;
                        //当前年月
                        String ym = new SimpleDateFormat("yyMM").format(new Date());

                        // 模块
                        int moduleID = 0;
                        for (ModuleEnum em : ModuleEnum.values()) {
                            if ((em.getName().equals("document"))||(em.getName().equals("workflow"))) {
                                moduleID = em.getIndex();
                            }
                        }

                        byte mid = (byte) moduleID;

                        Attachment attachment1 = new Attachment();
                        // 保存进数据库
                        attachment1 = new Attachment();
                        attachment1.setAttachId(attachID);
                        attachment1.setModule(mid);
                        attachment1.setAttachFile(attachment.getAttachName());
                        attachment1.setAttachName(attachment.getAttachName());
                        attachment1.setYm(ym);
                        attachment1.setAttachSign(new Long(0));
                        attachment1.setDelFlag((byte) 0);
                        attachment1.setPosition((byte) 2);
                        attachment1.setIsImage((byte) 0);
                        long length = file.length();

                        attachment1.setFileSize(String.valueOf(file.length()));
                        attachment1.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

                        // 数据库切换
                        ContextHolder.setConsumerType(dbSource);
                        attachmentMapper.insertSelective(attachment1);
                        ContextHolder.setConsumerType(firstDBSource);

//                    String toPath = sb.toString() + System.getProperty("file.separator") + "attach" + System.getProperty("file.separator") + dbSource +
//                            System.getProperty("file.separator") + "document" + System.getProperty("file.separator") + attachment1.getYm();

                        String toPath=null;
                        if (documentOrg!=null){
                            toPath = sb.toString()  + System.getProperty("file.separator") + dbSource +
                                    System.getProperty("file.separator") + "document" + System.getProperty("file.separator") + attachment1.getYm();
                        }else if (flowRun!=null){
                            toPath = sb.toString()  + System.getProperty("file.separator") + dbSource +
                                    System.getProperty("file.separator") + "workflow" + System.getProperty("file.separator") + attachment1.getYm();
                        }



                        File file1 = new File(toPath);
                        // 目录是否存在
                        if (!file1.exists()) {
                            file1.mkdirs();
                        }
                        copyFile(path, toPath + System.getProperty("file.separator") + attachment1.getAttachId() + "." + attachment1.getAttachName());
                        if (documentOrg!=null){
                            documentOrg.setMainFile(attachment1.getAid()+"@"+attachment1.getYm()+"_"+attachment1.getAttachId());
                        }else if (flowRun!=null){
                            stringBuffer.append(attachment1.getAid()+"@"+attachment1.getYm()+"_"+attachment1.getAttachId()).append(",");
                            flowRun.setAttachmentId(stringBuffer.toString());
                        }
                    }
                }
            }
        }

        //正文
        if (documentOrg!=null && !StringUtils.checkNull(documentOrg.getMainAipFile()) && !StringUtils.checkNull(documentOrg.getMainAipFileName())) {
            List<Attachment> attachments = GetAttachmentListUtil.returnAttachment(documentOrg.getMainAipFileName(), documentOrg.getMainAipFile(), firstDBSource, "document");
            if (attachments != null && attachments.size() > 0) {
                Attachment attachment = attachments.get(0);
                // 获取文件path
//                String path = sb.toString() + System.getProperty("file.separator") + "attach" + System.getProperty("file.separator") + firstDBSource +
//                        System.getProperty("file.separator") + "document" + System.getProperty("file.separator") + attachment.getYm() + System.getProperty("file.separator") + attachment.getAttachId() + "." + attachment.getAttachName();
                String path = sb.toString()  + System.getProperty("file.separator") + firstDBSource +
                        System.getProperty("file.separator") + "document" + System.getProperty("file.separator") + attachment.getYm() + System.getProperty("file.separator") + attachment.getAttachId() + "." + attachment.getAttachName();

                File file = new File(path);
                // 如果文件不存在
                if (!file.exists()) {
                    documentOrg.setMainAipFile("");
                    documentOrg.setMainAipFileName("");
                } else {
                    String attachID = String.valueOf(Math.abs((int) System.currentTimeMillis()));
                    //当前年月
                    String ym = new SimpleDateFormat("yyMM").format(new Date());

                    // 模块
                    int moduleID = 0;
                    for (ModuleEnum em : ModuleEnum.values()) {
                        if (em.getName().equals("document")) {
                            moduleID = em.getIndex();
                        }
                    }

                    byte mid = (byte) moduleID;

                    Attachment attachment1 = new Attachment();
                    // 保存进数据库
                    attachment1 = new Attachment();
                    attachment1.setAttachId(attachID);
                    attachment1.setModule(mid);
                    attachment1.setAttachFile(attachment.getAttachName());
                    attachment1.setAttachName(attachment.getAttachName());
                    attachment1.setYm(ym);
                    attachment1.setAttachSign(new Long(0));
                    attachment1.setDelFlag((byte) 0);
                    attachment1.setPosition((byte) 2);
                    attachment1.setIsImage((byte) 0);
                    attachment1.setFileSize(String.valueOf(file.length()));
                    attachment1.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

                    // 数据库切换
                    ContextHolder.setConsumerType(dbSource);
                    attachmentMapper.insertSelective(attachment1);
                    ContextHolder.setConsumerType(firstDBSource);

//                    String toPath = sb.toString() + System.getProperty("file.separator") + "attach" + System.getProperty("file.separator") + dbSource +
//                            System.getProperty("file.separator") + "document" + System.getProperty("file.separator") + attachment1.getYm();
                    String toPath = sb.toString() +  System.getProperty("file.separator") + dbSource +
                            System.getProperty("file.separator") + "document" + System.getProperty("file.separator") + attachment1.getYm();


                    File file1 = new File(toPath);
                    // 目录是否存在
                    if (!file1.exists()) {
                        file1.mkdirs();
                    }
                    copyFile(path, toPath + System.getProperty("file.separator") + attachment1.getAttachId() + "." + attachment1.getAttachName());
                    documentOrg.setMainAipFile(attachment1.getAid()+"@"+attachment1.getYm()+"_"+attachment1.getAttachId());
                }
            }
        }
    }


    public List<String> copyWordAndAIPFile2(FlowRun flowRun,DocumentOrg documentOrg,DocumentModelWithBLOBs documentModel ,String firstDBSource, String dbSource) throws IOException {
        ResourceBundle rb = ResourceBundle.getBundle("upload");
        String osName = System.getProperty("os.name");
        StringBuffer sb = new StringBuffer();
        StringBuffer buffer=new StringBuffer();
        if(osName.toLowerCase().startsWith("win")){
            //sb=sb.append(rb.getString("upload.win"));
            //判断路径是否是相对路径，如果是的话，加上运行的路径
            String uploadPath = rb.getString("upload.win");
            if(uploadPath.indexOf(":")==-1){
                //获取运行时的路径
                String basePath = this.getClass().getClassLoader().getResource(".").getPath()+ File.pathSeparator;
                //获取截取后的路径
                String str2 = "";
                if(basePath.indexOf("/xoa")!=-1){
                    //获取字符串的长度
                    int length = basePath.length();
                    //返回指定字符在此字符串中第一次出现处的索引
                    int index = basePath.indexOf("/xoa");
                    //从指定位置开始到指定位置结束截取字符串
                    str2=basePath.substring(0,index);
                }
                sb = sb.append(str2 + "/xoa");
            }
            sb.append(uploadPath);
            buffer=buffer.append(rb.getString("upload.win"));
        }else{
            sb=sb.append(rb.getString("upload.linux"));
            buffer=buffer.append(rb.getString("upload.linux"));
        }

        if ((flowRun!=null && !StringUtils.checkNull(flowRun.getAttachmentId()) && !StringUtils.checkNull(flowRun.getAttachmentName()))|| (documentOrg!=null && !StringUtils.checkNull(documentOrg.getMainFile()) && !StringUtils.checkNull(documentOrg.getMainFileName()))) {
            List<Attachment> attachments = null;
            if (documentOrg!=null){

                attachments=GetAttachmentListUtil.returnAttachment(documentOrg.getMainAipFile(), documentOrg.getMainAipFileName(), firstDBSource, "document");
            }else if (flowRun!=null){
                attachments=GetAttachmentListUtil.returnAttachment(flowRun.getAttachmentName(), flowRun.getAttachmentId(), firstDBSource, "workflow");
            }
            if (attachments != null && attachments.size() > 0) {
                StringBuffer stringBuffer=new StringBuffer();
                for (Attachment attachment:attachments) {

                    // 获取文件path
//                String path = sb.toString() + System.getProperty("file.separator") + "attach" + System.getProperty("file.separator") + firstDBSource +
//                        System.getProperty("file.separator") + "document" + System.getProperty("file.separator") + attachment.getYm() + System.getProperty("file.separator") + attachment.getAttachId() + "." + attachment.getAttachName();

                    //---------------------------------判断是否为Linux开始-------------------------------------


                    String attachmentName = attachment.getAttachName();
                    try {
                        int codeLength = attachmentName.getBytes("UTF-8").length;
                        String type = attachmentName.substring(attachmentName.lastIndexOf("."));
                        if(codeLength>230&&osName.toLowerCase().startsWith("linu")){//判断
                            String s = (new BASE64Encoder()).encodeBuffer((attachmentName.substring(0,attachmentName.lastIndexOf("."))).getBytes(StandardCharsets.UTF_8));
                            String regEx=("[\\s\\\\/:\\*\\?\\\"<>\\|]");
                            attachmentName=(Pattern.compile(regEx).matcher(s).replaceAll("").trim().substring(0,100))+type;
                        }
                    }catch (Exception e){

                    }

                    //---------------------------------判断是否为Linux结束-------------------------------------




                    String path = null;
                    if (documentOrg!=null){
                        path=sb.toString() + System.getProperty("file.separator") + firstDBSource +
                                System.getProperty("file.separator") + "document" + System.getProperty("file.separator") + attachment.getYm() + System.getProperty("file.separator") + attachment.getAttachId() + "." + attachmentName;
                    }else if (flowRun!=null){
                        path=sb.toString() + System.getProperty("file.separator") + firstDBSource +
                                System.getProperty("file.separator") + "workflow" + System.getProperty("file.separator") + attachment.getYm() + System.getProperty("file.separator") + attachment.getAttachId() + "." + attachmentName;
                    }


                    File file = new File(path);
                    // 如果文件不存在
                    if (!file.exists()) {
                        if (documentOrg!=null){
                            documentOrg.setMainFile("");
                            documentOrg.setMainFileName("");
                        }else if (flowRun!=null){
                            flowRun.setAttachmentId("");
                            flowRun.setAttachmentName("");
                        }
                    } else {
                        String attachID =String.valueOf(Math.abs((int) System.currentTimeMillis())) ;
                        //当前年月
                        String ym = new SimpleDateFormat("yyMM").format(new Date());

                        // 模块
                        int moduleID = 0;
                        for (ModuleEnum em : ModuleEnum.values()) {
                            if ((em.getName().equals("document"))||(em.getName().equals("workflow"))) {
                                moduleID = em.getIndex();
                            }
                        }

                        byte mid = (byte) moduleID;

                        Attachment attachment1 = new Attachment();
                        // 保存进数据库
                        attachment1 = new Attachment();
                        attachment1.setAttachId(attachID);
                        attachment1.setModule(mid);
                        attachment1.setAttachFile(attachment.getAttachName());
                        attachment1.setAttachName(attachment.getAttachName());
                        attachment1.setYm(ym);
                        attachment1.setAttachSign(new Long(0));
                        attachment1.setDelFlag((byte) 0);
                        attachment1.setPosition((byte) 2);
                        attachment1.setIsImage((byte) 0);
                        DecimalFormat df = new DecimalFormat("#");
                        String fileSizeString = "";
                        String wrongSize = "0B";

                        if (file.length() < 1024) {
                            fileSizeString = df.format((double) file.length()) + "B";
                        } else if (file.length() < 1048576) {
                            fileSizeString = df.format(Math.rint((double) file.length() / 1024)) + "KB";
                        } else if (file.length() < 1073741824) {
                            fileSizeString = df.format(Math.rint((double) file.length() / 1048576)) + "MB";
                        } else {
                            fileSizeString = df.format(Math.rint((double) file.length() / 1073741824)) + "GB";
                        }

                        attachment1.setSize(String.valueOf(fileSizeString));
                        attachment1.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

                        // 数据库切换
                        ContextHolder.setConsumerType(dbSource);
                        attachmentMapper.insertSelective(attachment1);
                        ContextHolder.setConsumerType(firstDBSource);

//                    String toPath = sb.toString() + System.getProperty("file.separator") + "attach" + System.getProperty("file.separator") + dbSource +
//                            System.getProperty("file.separator") + "document" + System.getProperty("file.separator") + attachment1.getYm();

                        String toPath=null;
                        if (documentOrg!=null){
                            toPath = sb.toString()  + System.getProperty("file.separator") + dbSource +
                                    System.getProperty("file.separator") + "document" + System.getProperty("file.separator") + attachment1.getYm();
                        }else if (flowRun!=null){
                            toPath = sb.toString()  + System.getProperty("file.separator") + dbSource +
                                    System.getProperty("file.separator") + "workflow" + System.getProperty("file.separator") + attachment1.getYm();
                        }


                        File file1 = new File(toPath);
                        // 目录是否存在
                        if (!file1.exists()) {
                            file1.mkdirs();
                        }

                        //复制后生成的文件名(attachmentName为复制前的文件名成，)
                        copyFile(path, toPath + System.getProperty("file.separator") + attachment1.getAttachId() + "." + attachmentName);
//                        documentOrg.setMainAipFile(attachment1.getAid()+"@"+attachment1.getYm()+"_"+attachment1.getAttachId());
                        FlowRun flowRun1=new FlowRun();
                        flowRun1.setRunId(flowRun.getRunId());

                        if (documentOrg!=null){
                            documentOrg.setMainFile(attachment1.getAid()+"@"+attachment1.getYm()+"_"+attachment1.getAttachId());
                        }else if (flowRun!=null){
                            stringBuffer.append(attachment1.getAid()+"@"+attachment1.getYm()+"_"+attachment1.getAttachId()).append(",");
                            flowRun.setAttachmentId(stringBuffer.toString());
                        }
                        flowRun1.setAttachmentId(flowRun.getAttachmentId());
                        flowRun1.setAttachmentName(attachment1.getAttachName());
                        wfeFlowRunMapper.updateFu(flowRun1);
                    }
                }
            }
        }

        //正文
        documentOrg=new DocumentOrg();
        documentOrg.setMainAipFile(documentModel.getMainAipFile());
        documentOrg.setMainAipFileName(documentModel.getMainAipFileName());
        if (documentOrg!=null && !StringUtils.checkNull(documentOrg.getMainAipFile()) && !StringUtils.checkNull(documentOrg.getMainAipFileName())) {
            List<Attachment> attachments = GetAttachmentListUtil.returnAttachment(documentOrg.getMainAipFileName(), documentOrg.getMainAipFile(), firstDBSource, "document");
            List<String> list=new ArrayList<>();
            if (attachments != null && attachments.size() > 0) {
                Attachment attachment = attachments.get(0);
                // 获取文件path
//                String path = sb.toString() + System.getProperty("file.separator") + "attach" + System.getProperty("file.separator") + firstDBSource +
//                        System.getProperty("file.separator") + "document" + System.getProperty("file.separator") + attachment.getYm() + System.getProperty("file.separator") + attachment.getAttachId() + "." + attachment.getAttachName();
                String path = sb.toString()  + System.getProperty("file.separator") + firstDBSource +
                        System.getProperty("file.separator") + "document" + System.getProperty("file.separator") + attachment.getYm() + System.getProperty("file.separator") + attachment.getAttachId() + "." + attachment.getAttachName();

                File file = new File(path);
                // 如果文件不存在
                if (!file.exists()) {
                    documentOrg.setMainAipFile("");
                    documentOrg.setMainAipFileName("");
                } else {
                    String attachID = String.valueOf(Math.abs((int) System.currentTimeMillis()));
                    //当前年月
                    String ym = new SimpleDateFormat("yyMM").format(new Date());

                    // 模块
                    int moduleID = 0;
                    for (ModuleEnum em : ModuleEnum.values()) {
                        if (em.getName().equals("document")) {
                            moduleID = em.getIndex();
                        }
                    }

                    byte mid = (byte) moduleID;

                    Attachment attachment1 = new Attachment();
                    // 保存进数据库
                    attachment1 = new Attachment();
                    attachment1.setAttachId(attachID);
                    attachment1.setModule(mid);
                    attachment1.setAttachFile(attachment.getAttachName());

                    attachment1.setAttachName(attachment.getAttachName());
                    attachment1.setYm(ym);
                    attachment1.setAttachSign(new Long(0));
                    attachment1.setDelFlag((byte) 0);
                    attachment1.setPosition((byte) 2);
                    attachment1.setIsImage((byte) 0);

                    DecimalFormat df = new DecimalFormat("#.0");
                    String fileSizeString = "";
                    String wrongSize = "0B";

                    if (file.length() < 1024) {
                        fileSizeString = df.format((double) file.length()) + "B";
                    } else if (file.length() < 1048576) {
                        fileSizeString = df.format((double) file.length() / 1024) + "KB";
                    } else if (file.length() < 1073741824) {
                        fileSizeString = df.format((double) file.length() / 1048576) + "MB";
                    } else {
                        fileSizeString = df.format((double) file.length() / 1073741824) + "GB";
                    }

                    attachment1.setSize(String.valueOf(fileSizeString));
                    attachment1.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

                    // 数据库切换
                    ContextHolder.setConsumerType(dbSource);
                    attachmentMapper.insertSelective(attachment1);
                    ContextHolder.setConsumerType(firstDBSource);

//                    String toPath = sb.toString() + System.getProperty("file.separator") + "attach" + System.getProperty("file.separator") + dbSource +
//                            System.getProperty("file.separator") + "document" + System.getProperty("file.separator") + attachment1.getYm();
                    String toPath = sb.toString() +  System.getProperty("file.separator") + dbSource +
                            System.getProperty("file.separator") + "document" + System.getProperty("file.separator") + attachment1.getYm();


                    File file1 = new File(toPath);
                    // 目录是否存在
                    if (!file1.exists()) {
                        file1.mkdirs();
                    }
                    copyFile(path, toPath + System.getProperty("file.separator") + attachment1.getAttachId() + "." + attachment1.getAttachName());
                    documentOrg.setMainAipFile(attachment1.getAid()+"@"+attachment1.getYm()+"_"+attachment1.getAttachId());
                    list.add(documentOrg.getMainAipFile());
                    list.add(attachment1.getAttachName());
                }
            }
        return list;
        }else {
            return  null;
        }
    }




    /**
     * 作者: 张航宁
     * 日期: 2018/3/14
     * 说明: 拷贝公共接口
     */
    public void copyFile(String from, String to) throws IOException {
        FileInputStream ins = new FileInputStream(new File(from));
        FileOutputStream out = new FileOutputStream(new File(to));
        byte[] b = new byte[1024];
        int n=0;
        while((n=ins.read(b))!=-1){
            out.write(b, 0, n);
        }

        ins.close();
        out.close();
    }


}
